package com.huo.base.controller;

import org.openqa.selenium.server.ClasspathResourceLocator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description:
 * @USER: yangw
 * @Date: 2018/3/31
 * @Time: 22:08
 * @version:1.0
 */
@Controller
public class FileController {



    @RequestMapping(value = "/getupload",method = RequestMethod.GET)
    public String getRequest(ModelMap modelMap){
        modelMap.addAttribute( "test" ,"测试");
        return "a";
    }

 @RequestMapping(value = "/res",method = RequestMethod.GET)
    public String res(ModelMap modelMap){
        return "res";
    }


    /**
     * 上传处理
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public void uploadImage(@RequestParam("upload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        //解决跨域问题
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        PrintWriter out = null;
        String callback = request.getParameter("CKEditorFuncNum");
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 组装返回url，以便于ckeditor定位图片
        String fileUrl = "http://springforall.ufile.ucloud.com.cn/images/logo.png";
        // 将上传的图片的url返回给ckeditor
      //  String script = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ", '" + fileUrl + "');</script>";

        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
                + ",'" + fileUrl  + "','')");
        out.println("</script>");
       // out.println(script);
        out.flush();
        out.close();

        //return "SUCCESS";
    }


    @RequestMapping(value = "/upload3")
    @ResponseBody
    public void uploadImage3(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType( "text/html;UTF-8" );
       // response.setCharacterEncoding( "UTF-8" );

        //设置响应头 setHeader
        //Refresh消息头 定时重定向，设置2秒后，定时重定向一个新的地址，背景：完成某个操作，不用return到一个新的页面
       // response.setHeader( "Refresh","2;URL=http://www.baidu.com" );//String u = "URL=http://www.baidu.com";

        //Location消息头 要和状态码一块使用，才能重定向。response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader( "Location","http://www.baidu.com" );

        //设置http缓存（get请求）
        response.setHeader( "pragma","no-cache" );
        response.setHeader( "Cache-Control","no-cache" );
        response.setHeader( "expires","0" );


        response.setHeader( "X-Frame-Options","SAMEORIGIN" );


        //addHeader
        response.addHeader( "header","指定响应头中的值");
        //response.addHeader( "header", URLEncoder.encode( "指定响应头中的值","UTF-8"  ) );


        //设置响应码
       // response.setStatus(HttpServletResponse.SC_OK);

        //设置响应内容


        //重定向
       // response.sendRedirect( "http://www.baidu.com" );

    }

    @GetMapping(value = "/disposition")
    public void disposition(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setHeader( "Content-Disposition","attachment;filename=email.png" );
        String path = request.getServletContext().getContextPath();//( "resources/static/images/email.png" );
        //InputStream in = request.getServletContext().getResourceAsStream( "resources/static/images/email.png" );
        FileInputStream in = new FileInputStream(path);
        int len = 0;
        byte t[] = new byte[2024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read())>0){
            System.out.println(len);
            System.out.println(in.read()+"====");
            out.write( t,0,len );

        }

    }

    /**
     * 字节流
     * @param response
     * @throws IOException
     */
    @GetMapping("/outputStream")
    public void outputStream(HttpServletResponse response) throws IOException {
        response.setHeader( "Content-Type","text/html;charset=UTF-8" );
        String data = "你好";
        byte [] bytes = data.getBytes("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 字符流，容易丢失数据
     * @param response
     * @throws IOException
     */
    @GetMapping("printWriter")
    public void printWriter(HttpServletResponse response) throws IOException {
        response.setHeader( "content-type","text/html;charset=utf-8" );//设置浏览器以什么编码显示
        String data = "printwriter输出流";
        PrintWriter printWriter = response.getWriter();
        printWriter.print( data );
        printWriter.flush();//强制将缓冲区中的数据输出，输出时只有缓存区满了，才会输出
        printWriter.close();
    }



    /**
     * 下载图片
     * @param response
     * @throws IOException
     */
    @GetMapping("/getPath")
    public void getPath(HttpServletResponse response) throws IOException {
        String path = ClassUtils.getDefaultClassLoader().getResource( "" ).getPath();
        System.out.println(path);
        FileInputStream fileInputStream = new FileInputStream( path+"/static/images/email.png" );
        //设置字节流
        //设置文件名 编码
        //告知浏览器要下载文件
        //输出
        OutputStream outputStream = response.getOutputStream();
        String fileName = "t.png";
        fileName = URLEncoder.encode( fileName,"UTF-8" );
       // response.setHeader( "content-disposition","attachment;filename="+fileName );//弹出对话框，让用户选择下载
        response.setHeader( "content-disposition","inline;filename="+fileName );//将图片直接显示在页面
        response.setHeader( "content-type","image/png" );
        byte be [] = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(be)) != -1){
         //  System.out.println("文件流读取字节："+fileInputStream.read(be));// 不能打印，不然下载的文件不完整损坏
            outputStream.write( be,0,len );//从下标0开始到下一个字节
        }
        outputStream.flush();//将缓存区输出
        outputStream.close();
        fileInputStream.close();

    }

    /**
     * 文件下载
     * @param response
     * @param request
     * @throws IOException
     */
    @GetMapping("/downFile")
    public void downFile(HttpServletResponse response,HttpServletRequest request) throws IOException {
        //1获取文件路径

        String path = ClassUtils.getDefaultClassLoader().getResource( "" ).getPath();
        String textPath = path+"/static/down.txt";
        FileInputStream  fileInputStream = new FileInputStream(textPath);
        // 输入输出流
       ServletOutputStream outputStream =  response.getOutputStream();
        // 读取文件内容 按照字节数组
        int len = 0;
        byte [] bytes = new byte[1024];
        while ((len = fileInputStream.read( bytes )) !=-1){
            outputStream.write( bytes,0 ,len );
        }
        String fileName ="file.txt";
        fileName = URLEncoder.encode( fileName,"utf-8" );
        // 设置文件下载响应头
        response.setHeader( "content-disposition","attachment;filename="+ fileName);
        response.setHeader( "content-type","text/pain" );
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }





}


